//
//  UserAccountViewModel.swift
//  WeiBo test
//
//  Created by Aquarius_wing on 16/5/6.
//  Copyright © 2016年 Wing. All rights reserved.
//

import UIKit
import AFNetworking

//ViewModel 将一些业务逻辑封装到 这个类里 让这个隔离的更加好
class UserAccountViewModel: NSObject {
//页面的事情来交给ViewModel来做
    
    //增加userAccount
    var account:UserAccount?
    
    //用户是否登录的属性
    var userLogin:Bool{
        return account?.access_token != nil
    }
    
    var  token:String?{
        if userLogin{
            return account?.access_token
        }else{
            return nil
        }
    }
    
    
    //在init方法中获取 用户账户
    override init() {
        account=UserAccount.loadAccount()
    }
    
    //加载用户的token
    //在封装在此类中,新增了可以返回错误信息的error,因为可能为空故而是可选类型
    func loadAccessToken(code:String,finished: (error:NSError?)->()){
        let urlString = "oauth2/access_token"
        let parameters=["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        NetWorkTools.sharedTools.requestJsonDict(HTTPMethod.POST, urlString: urlString, parameters: parameters) { (result, error) in
            if error != nil {
                print("loadAccessToken error!",error)
                finished(error: error)
                return
            }
            //得到数据,并且字典转模型
            print("loadAccessToken result",result)
            //给 access_token    remind_in       uid     expires_in      赋值
            let account = UserAccount(dict: result!)
            //获取用户信息
            self.loadUserInfo(account, finished: finished)
        }
        
    }
    
    //加载用户信息
    private func loadUserInfo(account:UserAccount,finished:(error:NSError?)->()){
        let urlString = "2/users/show.json"
        let parameters = ["access_token":account.access_token!,"uid":account.uid!]
        NetWorkTools.sharedTools.requestJsonDict(HTTPMethod.GET, urlString: urlString, parameters: parameters) { (result, error) in
            if error != nil{
                //如果错误存在则
                finished(error: error)
                print("loadUserInfo error!",error)
                return
            }
            //得到数据
            //给 头像    名字    赋值
            account.avatar_large = result!["avatar_large"] as? String
            account.name = result!["name"] as? String
            account.saveAccount()
            finished(error: nil)
        }
        
    }
}
